﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Com.ZX
{
    public delegate void ValueChangeHandler<T>(T oldValue, T newValue);
    public interface IBindable<T>
    {
        event ValueChangeHandler<T> OnValueChanged;
    }
    public class BindableProperty<T>:IBindable<T>
    {
        /// <summary>
        /// 绑定方向
        /// </summary>
        public enum BindingMode
        {
            /// <summary>
            /// 单向绑定源到前端
            /// </summary>
            OneWayS2T,
            /// <summary>
            /// 单向绑定前端到源
            /// </summary>
            OneWayT2S,
            /// <summary>
            /// 双向
            /// </summary>
            TwoWay
        }
        //public delegate void ValueChangeHandler(T oldValue, T newValue);
        //public ValueChangeHandler OnValueChanged;
        public event ValueChangeHandler<T> OnValueChanged;

        private T _Value;
        public T Value
        {
            get { return _Value; }
            set
            {
                if (!Equals(value, _Value))
                {
                    T old = _Value;
                    _Value = value;
                    OnValueChanged(old, _Value);
                }
            }
        }

        
      

        public override string ToString()
        {
            return Value != null ? Value.ToString() : "null";

        }

        /// <summary>
        /// 为View绑定属性
        /// </summary>
        /// <param name="target"></param>
        /// <param name="source"></param>
        /// <param name="mode"></param>
        public static void SetBinding<TargetT, SourceT>(object target, SourceT source, BindingMode mode) where SourceT : IBindable<TargetT>
        {
            if (mode != BindingMode.OneWayT2S)
            {
                source.OnValueChanged += (oldV, newV) =>
                {
                    //var temp = (TargetT)target;
                    //temp = newV;
                };
            }
            if (mode == BindingMode.OneWayS2T)
            {
                //source
            }
            //switch (mode)
            //{
            //    case BindingMode.OneWayS2T:
            //        source.OnValueChanged += (oldV, newV) =>
            //        {
            //            target = newV;
            //        };
            //        break;
            //    case BindingMode.OneWayT2S:
            //        break;
            //    case BindingMode.TwoWay:
            //        source.OnValueChanged += (oldV, newV) =>
            //        {
            //            target = newV;
            //        };
            //           //MsgManager.inst.AddListener()
            //        break;
            //    default:
            //        break;
            //}

        }

    }
}
